package com.daily.pump.activity;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.daily.pump.R;
import com.daily.pump.app.App;
import com.daily.pump.constants.ActivityRequestCode;
import com.daily.pump.constants.ExtraConstants;
import com.daily.pump.dialog.AddDeviceDialog;
import com.daily.pump.dialog.CompressSettingDialog;
import com.daily.pump.dialog.LoginDialog;
import com.daily.pump.dialog.ModifyPwdDialog;
import com.daily.pump.dialog.ScanDialog;
import com.daily.pump.dialog.ScanResultNextDialog;
import com.daily.pump.http.WifiSocketClient;
import com.daily.pump.http.WifiSocketManger;
import com.daily.pump.model.Device;
import com.daily.pump.model.SimpleWifiBean;
import com.daily.pump.utils.BarUtils;
import com.daily.pump.utils.DensityUtils;
import com.daily.pump.utils.GpsUtil;
import com.daily.pump.utils.StringUtils;
import com.daily.pump.utils.WifiUtil;
import com.daily.pump.widget.CompressView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.xunxi.mimi.ui.base.BaseActivity;
import com.xunxi.mimi.utils.LogUtil;
import com.xunxi.mimi.utils.ScreenUtils;
import com.xunxi.mimi.utils.ToastUtil;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class MainActivity extends BaseActivity {

    //登录
    private static final int TYPE_LOGIN = 0;
    //修改设备状态
    private static final int TYPE_MODIFY = 1;
    private static final int DELAY_TIME = 200;
    public static final float PERCENT = 0.75f;//气压总气压75%
    private CompressView mCompressView;
    private TextView mPercentT;

    @BindView(R.id.inflatable_ll)
    LinearLayout mInFlatableLl;

    @BindView(R.id.inflatable_fl)
    FrameLayout mInFlatableFl;

    @BindView(R.id.inflatable_tv)
    TextView mInFlatableTv;

    @BindView(R.id.stop_tv)
    TextView mStopTv;

    @BindView(R.id.soft_tv)
    TextView mSoftTv;

    @BindView(R.id.medium_tv)
    TextView mMediumTv;

    @BindView(R.id.firm_tv)
    TextView mFirmTv;

    @BindView(R.id.tv_custom)
    TextView mCustomTv;

    private int mAdjustValue;

    private Handler mHandler = new Handler();

    //设备列表点击连接
    private boolean isConning = false;

    //登录连接
    private boolean isLoginConning = false;

    //自动登录连接
    private boolean isAutoConning = false;

    private boolean isLoginSucc;

    private String mDeviceName;

    private SimpleWifiBean mLoginWifiBean;

    private Device autoLoginDevice;

    private ScanResultNextDialog mScanResultNextDialog;

    private LoginDialog mLoginDialog;

    private ModifyPwdDialog mModifyPwdDialog;

    private AddDeviceDialog mAddDeviceDialog;

    private int mLoginType;

    private Handler getHandler() {
        if (mHandler == null) {
            mHandler = new Handler();
        }
        return mHandler;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState, String tag) {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initView() {
        setStatusBarTintResource(R.color.transparent);
        ConstraintLayout parentView = findViewById(R.id.parent);
        parentView.setPadding(0, BarUtils.getStatusBarHeight(this), 0, 0);

        FrameLayout compressFly = findViewById(R.id.compress_fly);
        boolean mIsMaxAspect = ScreenUtils.getScreenHeight(this) / (float) ScreenUtils.getScreenWidth(this) > 1.87;
        //全面屏适配
        if (mIsMaxAspect) {
            compressFly.setTranslationY(-DensityUtils.dp2px(this, 10));

            ConstraintLayout.LayoutParams flatableParams = (ConstraintLayout.LayoutParams) mInFlatableLl.getLayoutParams();
            flatableParams.bottomMargin = DensityUtils.dp2px(this, 90);
        } else {
            compressFly.setTranslationY(-DensityUtils.dp2px(this, 30));

            ConstraintLayout.LayoutParams flatableParams = (ConstraintLayout.LayoutParams) mInFlatableLl.getLayoutParams();
            flatableParams.bottomMargin = DensityUtils.dp2px(this, 60);
        }

        mCompressView = findViewById(R.id.compress_view);
        mPercentT = findViewById(R.id.percent_tv);
        mPercentT.setTextColor(getResources().getColor(R.color.color_disable));
        mCompressView.setCompressViewListener(new CompressView.CompressViewListener() {
            @Override
            public void getCompressValue(float percent) {
                int resultValue = (int) (percent * 100);
                mPercentT.setText(resultValue == 0 ? "00" : (resultValue + ""));

                if (resultValue == mAdjustValue) {
                    mCompressView.stopRotateAnim();
                }
            }

            @Override
            public void onAdjustCompress(float percent) {
                int adjustValue = (int) (percent * 100);
                if (mAdjustValue != adjustValue){
                    mAdjustValue = adjustValue;

                    WifiSocketManger.getInstance().onSetCompressValue(mAdjustValue);
                    mCompressView.startRotateAnim();
                }
            }
        });

        mInFlatableFl.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                startInflation();
                return true;
            }
        });
        mInFlatableFl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    //如果
                    stopInflation();
                }
                return false;
            }
        });

        mSoftTv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showSettingCompressDialog(CompressSettingDialog.TYPE_SOFT);
                return true;
            }
        });

        mMediumTv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showSettingCompressDialog(CompressSettingDialog.TYPE_MEDIUM);
                return true;
            }
        });

        mFirmTv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showSettingCompressDialog(CompressSettingDialog.TYPE_FIRM);
                return true;
            }
        });

        setDeviceEnable(false);
    }

    private void showSettingCompressDialog(int type) {
        int value = mAdjustValue;
        Device loginDevice = App.getInstance().getLoginDevice();
        if (loginDevice != null) {
            if (type == CompressSettingDialog.TYPE_SOFT) {
                value = loginDevice.softValue;
            } else if (type == CompressSettingDialog.TYPE_MEDIUM) {
                value = loginDevice.mediumValue;
            } else if (type == CompressSettingDialog.TYPE_FIRM) {
                value = loginDevice.firmValue;
            }
        }
        CompressSettingDialog compressSettingDialog = CompressSettingDialog.newInstance(type, value);
        compressSettingDialog.setCompressSettingListener(new CompressSettingDialog.CompressSettingListener() {
            @Override
            public void onSetting(int type, int progress) {
                mAdjustValue = progress;
                mCompressView.setProgress(progress / 100.0f);
                WifiSocketManger.getInstance().onSetCompressValue(progress);
            }
        });
        compressSettingDialog.show(getSupportFragmentManager());
    }

    @Override
    protected void initPresenter() {
    }

    @Override
    protected void initValue() {
        autoLoginDevice = App.getInstance().getLoginDevice();
        if (autoLoginDevice != null) {
            mCustomTv.setText(StringUtils.subStringM(autoLoginDevice.loginName, 7));
            boolean connectTargetWifi = WifiUtil.connectTargetWifi(MainActivity.this, autoLoginDevice.wifiBean);
            if (connectTargetWifi) {
                isAutoConning = true;
                connectDevice();
            }
        } else {
            showScanDialog();
        }
        initBroadcast();
    }

    private void initBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(new WifiReceiver(this), filter);
    }

    private void connectDevice() {
        onStopGetCompressValueTimer();
        WifiSocketManger.getInstance().connnect(new WifiSocketManger.OnWiFiSocketListener() {
            @Override
            public void onRespnse(int code, float value) {
                LogUtil.error(MainActivity.class, "onRespnse code:" + code + "value:" + value);
                if (code == WifiSocketClient.CONNECTED_SUCC) {
                    WifiSocketManger.getInstance().getCompressValue(mAdjustValue);
                    if (isLoginConning) {
                        isLoginConning = false;
                        if (mScanResultNextDialog != null) {
                            mScanResultNextDialog.hideProgress();
                            mScanResultNextDialog.dismissAllowingStateLoss();
                        }
                        showLoginDialog(mDeviceName);
                    }
                    if (isAutoConning) {
                        isAutoConning = false;
                        if (autoLoginDevice != null) {
                            WifiSocketManger.getInstance().doLogin(autoLoginDevice.loginName, autoLoginDevice.password);
                        }
                    }
                } else if (code == WifiSocketClient.SEND_RESPONSE) {
                    mCompressView.updateProgress(value / 100f);
                } else if (code == WifiSocketClient.RESPONSE_TIMEOUT) {
                    setDeviceEnable(false);
//                    mListAdapter.clearSelect();
                    isLoginSucc = false;
                    if (isConning) {
                        isConning = false;
                        if (mAddDeviceDialog != null) {
                            mAddDeviceDialog.clearSelect();
                        }
                        ToastUtil.show(MainActivity.this, "connect timeout, please check device open");
                    }
                    if (isLoginConning) {
                        isLoginConning = false;
                        if (mScanResultNextDialog != null) {
                            mScanResultNextDialog.hideProgress();
                        }
                        ToastUtil.show(MainActivity.this, "connect device fail");
                    }

                    //自动连接失败，toast提醒
                    if (isAutoConning) {
                        isAutoConning = false;
                        if (mAddDeviceDialog != null) {
                            mAddDeviceDialog.clearSelect();
                        }
                        ToastUtil.show(MainActivity.this, "connect timeout, please check device open");
                    }
                }
            }

            @Override
            public void loginSucc() {
                mCompressView.setEnableCompress(true);
                setDeviceEnable(true);
                mPercentT.setTextColor(getResources().getColor(R.color.color_enable));
                if (mAddDeviceDialog != null) {
                    mAddDeviceDialog.clearSelect();
                }
                if (mLoginDialog != null) {
                    if (mLoginType == TYPE_LOGIN){
                        Device device = mLoginDialog.saveLoginDevice(mLoginWifiBean, mDeviceName);
                        if (mAddDeviceDialog != null) {
                            mAddDeviceDialog.addDevice(device);
                            mAddDeviceDialog.dismiss();
                        }
                    }else if (mLoginType == TYPE_MODIFY){
                        Device modifyDevice = null;
                        if (mScanResultNextDialog != null){
                            modifyDevice = mScanResultNextDialog.getSelectDevice();
                        }
                        if (modifyDevice == null){
                            modifyDevice = App.getInstance().getLoginDevice();
                        }
                        Device device = mLoginDialog.modifyLoginDevice(mLoginWifiBean, mDeviceName, modifyDevice);
                        if (mAddDeviceDialog != null) {
                            mAddDeviceDialog.addDevice(device);
                            mAddDeviceDialog.dismiss();
                        }
                    }
                    mLoginDialog.dismissAllowingStateLoss();
                    mLoginDialog = null;
                } else if (autoLoginDevice != null) {
                    App.getInstance().setLoginDevice(autoLoginDevice);
                }

                if (mAddDeviceDialog != null) {
                    mAddDeviceDialog.dismiss();
                }
                ToastUtil.show(MainActivity.this, "Login Succ");
                isLoginSucc = true;
                startGetCompressValueTimer();
            }

            @Override
            public void loginFail() {
                if (mLoginDialog != null) {
                    mLoginDialog.hideProgress();
                }
            }

            @Override
            public void modifyPwdSucc() {
                ToastUtil.show(MainActivity.this, "modify succ");
                if (mModifyPwdDialog != null) {
                    mModifyPwdDialog.modifyLoginPwd();
                    mModifyPwdDialog.hideProgress();
                    mModifyPwdDialog.dismiss();
                }
            }

            @Override
            public void modifyPwdFail() {
                ToastUtil.show(MainActivity.this, "modify fail");
                if (mModifyPwdDialog != null) {
                    mModifyPwdDialog.hideProgress();
                }
            }
        });
    }

    /**
     * Desc:设置设备是否可用状态
     * <p>
     * Author: [李豫]
     * Date: 2020-11-11
     *
     * @param enable 不可用置灰
     */
    private void setDeviceEnable(boolean enable) {
        mCompressView.setEnableCompress(enable);
        mInFlatableTv.setEnabled(enable);
        mStopTv.setEnabled(enable);
        mSoftTv.setEnabled(enable);
        mMediumTv.setEnabled(enable);
        mFirmTv.setEnabled(enable);
    }

    /**
     * Desc:开始定时获取气压值
     * <p>
     * Author: [李豫]
     * Date: 2020-09-08
     */
    private void startGetCompressValueTimer() {
        if (isLoginSucc) {
            getHandler().removeCallbacks(getCompressValueRunnable);
            getHandler().postDelayed(getCompressValueRunnable, DELAY_TIME);
        }
    }

    /**
     * Desc:停止获取气压值
     * <p>
     * Author: [李豫]
     * Date: 2020-09-08
     */
    private void onStopGetCompressValueTimer() {
        LogUtil.error(MainActivity.class, "onStopGetCompressValueTimer");
        getHandler().removeCallbacks(getCompressValueRunnable);
    }

    private Runnable getCompressValueRunnable = new Runnable() {
        @Override
        public void run() {
            WifiSocketManger.getInstance().getCompressValue(mAdjustValue);
            getHandler().postDelayed(this, DELAY_TIME);
            LogUtil.error(MainActivity.class, "startGetCompressValueTimer");
        }
    };

    /**
     * Desc:开始充气
     * <p>
     * Author: [李豫]
     * Date: 2020-09-08
     */
    private void startInflation() {
        onStopGetCompressValueTimer();
        getHandler().removeCallbacks(mInflationRunnable);
        getHandler().post(mInflationRunnable);
        if (mCompressView != null) {
            mCompressView.startRotateAnim();
        }
    }

    /**
     * Desc:停止充气
     * <p>
     * Author: [李豫]
     * Date: 2020-09-08
     */
    private void stopInflation() {
        getHandler().removeCallbacks(mInflationRunnable);
        if (mCompressView != null) {
            mCompressView.stopRotateAnim();
        }
        startGetCompressValueTimer();
    }

    private Runnable mInflationRunnable = new Runnable() {
        @Override
        public void run() {
            WifiSocketManger.getInstance().onInflatable();
            getHandler().postDelayed(this, DELAY_TIME);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        startGetCompressValueTimer();
    }

    @Override
    protected void onPause() {
        super.onPause();

        onStopGetCompressValueTimer();
    }

    @OnClick({R.id.stop_tv, R.id.soft_tv, R.id.medium_tv, R.id.firm_tv, R.id.percent_tv, R.id.tv_custom})
    public void OnClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.stop_tv) {
            WifiSocketManger.getInstance().onStop();
            mCompressView.stopRotateAnim();
        } else if (viewId == R.id.soft_tv) {
            Device loginDevice = App.getInstance().getLoginDevice();
            if (loginDevice != null) {
                int softValue = loginDevice.softValue;
                mAdjustValue = softValue;
                WifiSocketManger.getInstance().onSPress(softValue);
                if (mCompressView != null) {
                    mCompressView.setProgress(mAdjustValue / 100f);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mCompressView.startRotateAnim();
                        }
                    }, 200);
                }
            }
        } else if (viewId == R.id.medium_tv) {
            Device loginDevice = App.getInstance().getLoginDevice();
            if (loginDevice != null) {
                int mediumValue = loginDevice.mediumValue;
                mAdjustValue = mediumValue;
                WifiSocketManger.getInstance().onMPress(mediumValue);
                if (mCompressView != null) {
                    mCompressView.setProgress(mAdjustValue / 100f);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mCompressView.startRotateAnim();
                        }
                    }, 200);
                }
            }
        } else if (viewId == R.id.firm_tv) {
            Device loginDevice = App.getInstance().getLoginDevice();
            if (loginDevice != null) {
                int firmValue = loginDevice.firmValue;
                mAdjustValue = firmValue;
                WifiSocketManger.getInstance().onFPress(firmValue);
                if (mCompressView != null) {
                    mCompressView.setProgress(mAdjustValue / 100f);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mCompressView.startRotateAnim();
                        }
                    }, 200);
                }
            }
        } else if (viewId == R.id.percent_tv) {
            showSettingCompressDialog(CompressSettingDialog.TYPE_SETTING_VALUE);
        } else if (viewId == R.id.tv_custom) {
            showAddDeviceDialog();
        }
    }

    /**
     * Desc:显示
     * <p>
     * Date: 2020-11-11
     */
    private void showAddDeviceDialog() {
        if (mAddDeviceDialog == null) {
            mAddDeviceDialog = AddDeviceDialog.newInstance();
            mAddDeviceDialog.setAddDeviceDialogListener(new AddDeviceDialog.AddDeviceDialogListener() {
                @Override
                public void onConnDevice(Device device) {
                    autoLoginDevice = device;
                    boolean connectTargetWifi = WifiUtil.connectTargetWifi(MainActivity.this, autoLoginDevice.wifiBean);
                    if (connectTargetWifi) {
                        isAutoConning = true;
                        connectDevice();
                    }
                }

                @Override
                public void onAddDevice() {
                    boolean oPen = GpsUtil.isOPen(MainActivity.this);
                    if (oPen) {
                        startScan();
                    } else {
                        openGPS();
                    }
                }

                @Override
                public void onModifyDevice(Device device) {
                    if (mAddDeviceDialog != null){
                        mAddDeviceDialog.dismiss();
                    }
                    showDeviceNextDialog(device, TYPE_MODIFY);
                }
            });
        }
        mAddDeviceDialog.show(getSupportFragmentManager());
    }

    private void openGPS() {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setTitle("Open GPS")
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Open", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, ActivityRequestCode.OPEN_GPS_REQUEST_CODE);
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }

    /**
     * 显示扫描弹框
     */
    private void showScanDialog() {
        ScanDialog scanDialog = ScanDialog.newInstance();
        scanDialog.setScanDialogListener(new ScanDialog.ScanDialogListener() {
            @Override
            public void onDismiss() {

            }

            @Override
            public void onStartScan() {
                startScan();
            }
        });
        scanDialog.show(getSupportFragmentManager());
    }

    /**
     * Desc:显示扫描tank
     * <p>
     * Author: [李豫]
     * Date: 2020-10-24
     */
    private void startScan() {
        new RxPermissions(this).request(Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    if (mAddDeviceDialog != null) {
                        mAddDeviceDialog.dismiss();
                    }
                    Intent intent = new Intent(MainActivity.this, ZxingScanActivity.class);
                    startActivityForResult(intent, ActivityRequestCode.SCAN_REQUEST_CODE);
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ActivityRequestCode.SCAN_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String scanResult = data.getStringExtra(ExtraConstants.DEVICE_NAME);
                Device device = new Device();
                device.deviceName = scanResult;
                showDeviceNextDialog(device, TYPE_LOGIN);
            }
        } else if (requestCode == ActivityRequestCode.OPEN_GPS_REQUEST_CODE) {
            boolean oPen = GpsUtil.isOPen(this);
            if (oPen) {
                startScan();
            }
        }
    }

    private void showDeviceNextDialog(Device device, int type) {
        this.mLoginType = type;
        mScanResultNextDialog = ScanResultNextDialog.newInstance(device);
        mScanResultNextDialog.setScanDialogListener(new ScanResultNextDialog.ScanDialogListener() {
            @Override
            public void onTurnLogin(SimpleWifiBean simpleWifiBean, String deviceName) {
                MainActivity.this.isLoginConning = true;
                MainActivity.this.mDeviceName = deviceName;
                MainActivity.this.mLoginWifiBean = simpleWifiBean;
                connectDevice();
            }

            @Override
            public void onDismiss() {
            }
        });
        mScanResultNextDialog.show(getSupportFragmentManager());
    }

    private void showLoginDialog(String deviceName) {
        mLoginDialog = LoginDialog.newInstance(deviceName);
        mLoginDialog.setScanDialogListener(new LoginDialog.ScanDialogListener() {
            @Override
            public void onLogin(String name, String password) {
                WifiSocketManger.getInstance().doLogin(name, password);
            }

            @Override
            public void onDismiss() {
            }

            @Override
            public void showModifyPwdDialog() {
                mModifyPwdDialog = ModifyPwdDialog.newInstance();
                mModifyPwdDialog.setScanDialogListener(new ModifyPwdDialog.ScanDialogListener() {
                    @Override
                    public void onModifyPwd(String deviceName, String oldPwd, String newPwd) {
                        WifiSocketManger.getInstance().modifyPassword(deviceName, oldPwd, newPwd);
                    }

                    @Override
                    public void onDismiss() {
                        showLoginDialog(mDeviceName);
                    }
                });
                mModifyPwdDialog.show(getSupportFragmentManager());
            }
        });
        mLoginDialog.show(getSupportFragmentManager());
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        WifiSocketManger.getInstance().onDestory();
        super.onDestroy();
    }

    private boolean isExit = false;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                Toast.makeText(this, getString(R.string.sys_exit), Toast.LENGTH_SHORT).show();
                isExit = true;
                new CountDownTimer(3000, 1000) {
                    @Override
                    public void onFinish() {
                        isExit = false;
                    }

                    @Override
                    public void onTick(long arg0) {
                    }

                }.start();
                return true;
            } else {
                App.getInstance().exit();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public static class WifiReceiver extends BroadcastReceiver {
        private static final String TAG = "wifiReceiver";

        private WeakReference<MainActivity> mActivity;

        public WifiReceiver() {
        }

        public WifiReceiver(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            //wifi连接上与否
            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                    if (mActivity != null){
                        MainActivity mainActivity = mActivity.get();
                        if (mainActivity != null){
                            Log.e(MainActivity.class.getSimpleName(), "getExtraInfo:"+info.getExtraInfo());
                            mainActivity.reconnect();
                        }
                    }
                }
            }
        }
    }

    private void reconnect() {
        //如果WiFi断开就重连
        autoLoginDevice = App.getInstance().getLoginDevice();
        if (autoLoginDevice != null) {
            boolean connectTargetWifi = WifiUtil.connectTargetWifi(MainActivity.this, autoLoginDevice.wifiBean);
            if (connectTargetWifi) {
                isAutoConning = true;
                connectDevice();
            }
        }
    }
}
